/**
 * 
 */
package com.peak.distribution.config.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.peak.distribution.jms.JmsProducerHandler;
import com.peak.spring.boot.api.web.JsonMessage;
import com.peak.spring.boot.builder.web.JsonBuilder;
import com.peak.spring.boot.tools.Servlets;

/**
 * @author Frank
 *
 */
@Component
public class SessionAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	@Autowired
	private JmsProducerHandler jmsProducerHandler;

	public SessionAuthenticationFailureHandler() {
		this("/login/fail");
	}

	public SessionAuthenticationFailureHandler(String defaultFailureUrl) {
		super(defaultFailureUrl);
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {

		// 记录登录日志
		jmsProducerHandler.sendLoginJms(request, Boolean.FALSE);

		// 如果是Ajax登录
		if (Servlets.isAjax(request)) {
			JsonMessage msg = JsonBuilder.message().content(convertErrorMessage(exception)).build();
			Servlets.sendJson(response, msg);
		} else {
			super.onAuthenticationFailure(request, response, exception);
		}
	}
	
	public String convertErrorMessage(AuthenticationException e) {
		String eName = e.getClass().getSimpleName();
		String error = null;
		switch (eName) {
		case "UsernameNotFoundException":
			error = "账户名不存在，";
			break;
		case "DisabledException":
			error = "您的账户由于某些原因已被禁用，请联系您的上级代理或";
			break;
		case "BadCredentialsException":
		default:
			error = "账户名与密码不匹配，";
			break;
		}
		return error + "请重新输入";
	}

}
